package no.hib.mod250.chat.client.view;

import no.hib.mod250.chat.client.controller.ChatController;
import no.hib.mod250.chat.client.model.Model;
import no.hib.mod250.chat.client.service.ChatService;
import no.hib.mod250.chat.client.util.R;
import no.hib.mod250.chat.client.view.View.DataObserver;

import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Panel;

public class LoginView extends View implements DataObserver {

	// VARIABLES

	Panel panel = new FlowPanel();

	Image imgLoader = new Image(R.Image.loader);
	HTML htmlLogin = new HTML();
	HTML htmlLogout = new HTML();

	// /VARIABLES

	// CONSTRUCTOR

	public LoginView(ChatController controller) {
		super(controller);

		controller.addDataObserver(this);

		// Add panel as widget
		initWidget(panel);
		
		doDraw();
	}

	// /CONSTRUCTOR

	// FUNCTIONS

	// ... DO

	@Override
	public void doDraw() {
		// Add img loader
		panel.add(imgLoader);
	}

	private void doDrawLogin(Model.UserAdmin user) {
		Anchor link = new Anchor("Login", user.getUrlLogin());
		htmlLogin.setHTML(link.toString());

		panel.remove(imgLoader);
		panel.remove(htmlLogout);
		panel.add(htmlLogin);
	}

	private void doDrawLogout(Model.UserAdmin user) {
		Anchor ancLogout = new Anchor("Logout", user.getUrlLogout());
		htmlLogout.setHTML(user.getNickname() + " - " + ancLogout);

		panel.remove(imgLoader);
		panel.remove(htmlLogin);
		panel.add(htmlLogout);
	}

	// ... /DO

	// ... ON

	@Override
	public void onDataResult(ChatService.Result result) {
		Model.UserAdmin user = result.getUser();

		if (user.isLoggedIn()) {
			doDrawLogout(user);
		} else {
			doDrawLogin(user);
		}
	}

	// ... /ON

	// /FUNCTIONS

}
